package com.cictec.middleware.gps.engine.position.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.Constants;
import com.cictec.middleware.commons.utils.log.MultiLog;
import com.cictec.middleware.core.entity.DeparterSchedule;
import com.cictec.middleware.core.entity.StandbyZone;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.exception.BusPositionHandlerException;
import com.cictec.middleware.gps.engine.position.BusPositionHandler;
import com.cictec.middleware.gps.engine.utils.MultiLogUtil;
import com.cictec.middleware.gps.service.BusLineService;
import com.cictec.middleware.gps.service.ScheduleService;

/**
 * 待发区判断！
 * 
 * @author zhou qi
 *
 */
@Component
public class BusPositionStandbyHandler  implements BusPositionHandler {
	
	private Logger logger = LoggerFactory.getLogger(BusPositionStandbyHandler.class);
	
	@Autowired
	private ScheduleService scheduleService;
	@Autowired
	private BusLineService busLineService;
	
	@Override
	public void onHandler(BusInstance busInstance) throws BusPositionHandlerException {
		
		MultiLog log = MultiLogUtil.getPositionJudgeLog(busInstance);
		
		
		StandbyZone sz = busLineService.getStandbyZoneByPosition(busInstance.getLineUuid(), busInstance.getLatitude(), busInstance.getLongitude());
		String standbyStatus = Constants.VAL_STANDBY_0;// 默认车辆不在待发区
		if (sz != null) {
			String lineType = Constants.VAL_LINE_NOT_SPEC;

			if (sz.getLineType() != null && !sz.getLineType().equals(Constants.VAL_LINE_NOT_SPEC)) {
				//线路没有指定，但是待发区指定了
				lineType = sz.getLineType();
				log.debug("【待发区判断】线路没有指定，但是待发区指定了 --->上下行  ：   {}",sz.getLineType());
			} else {
				// 线路没有指定 待发区也没有指定 ，根据时刻表查询。
				DeparterSchedule ds = scheduleService.getDeparterScheduleNext(busInstance.getTime(), busInstance.getLineUuid(), busInstance.getBusUuid());
				if (ds != null) {
					lineType = ds.getBrsdType();
				}else{
					lineType = Constants.VAL_LINE_UP;	// 进入待发区，待发区未指定上下行，默认上行
				}
				log.debug("【待发区判断】线路没有指定 待发区也没有指定 ，根据时刻表查询---> 上下行  ：   {}", lineType);
			}
			
			if(null != lineType){
				standbyStatus = lineType.equals(Constants.VAL_LINE_UP) ? Constants.VAL_STANDBY_1 : Constants.VAL_STANDBY_2;

				// 设置待发区的线路类型
				busInstance.setLineType(lineType);
				log.debug("【待发区判断】\t待发区 存在线路类型，不做  【方向判断】， LINE_TYPE：{}", lineType);
				
			}
		}
		
		busInstance.setAttributeStandBy(standbyStatus);
		logger.debug("【待发区判断】待发状态：{}, 上下行：{}", standbyStatus, busInstance.getLineType());
		
	}
	

}
